<template>
  <div id="scroll-content" ref="scrollBox" class="main-content">
    <iframe
      id="reportcontent"

      @load="iframeLoaded"
      sandbox="allow-scripts allow-same-origin"
      frameborder="no"
      border="0"
      marginwidth="0"
      marginheight="0"
      :srcdoc="reportHtmls"
      width="100%"
      height="100%"
      scrolling="yes"
    >
    </iframe>
  </div>
</template>

<script>
  import chartMixins from '../../components/mixins/chartMixins'
  export default {
    mixins: [chartMixins],
    name:'ReportPageContent',
    props:{
     reportId:{
      type:String,
      required: true
     },
     getTreeList:{
      type:Array,
      required: true
     },
     positionId:{
      type:String
     },
     inputSearch:{
      type:String,
      required: true
     },
     searchIndex:{
       type:Number,
       required: true
     },
     inputPage:{
      type:Number,
      required: true
     },
     initOnce: {
       type: Boolean,
       required: true
     },
     scaleSize:{
        type:Number,
        required: true
     },
     fixId:{
        type:String,
        required: true
     },
   },
    data(){
      return {
        showIframe: false,  //展示iframe页面
        iframeTimer: '', //报告初始化页面计时器
        reportHtmls:'',
        isEchartsData:[],
        chartData:{},
        homeEcharts:null,
        inputChange: false,
        pageHeightA4: ((297 * 96) / 25.4 + 10).toFixed(2),// A4纸高度，加上margin
        lastInputPage: 1
      }
    },
    watch:{
      reportId:{
        handler(a){
          this.getReport(a)
        },
      },
      positionId:{
        handler(a){
          console.log(a);
          if(a) {
            this.positioning(a)
          }

        }
      },
      inputSearch:{
        handler(){
          this.findInPage()
        }
      },
      searchIndex:{
        handler(){
        if(this.totalIndex>0){
        this.highlightCurrentToken()
        }
        }
      }
    },
    created() {


    },
    methods:{
      /**
       * 初始化
       */
      iframeLoaded() {
        // 初始化页面的scale
        console.log("iframe加载");
        this.getReport(this.reportId);
        this.reDraw()
        let that = this
        reportcontent.contentWindow.document.body.onscroll = function() {
          that.scrollListen();

        }

        // 给iframe页面 添加onclick方法
        reportcontent.contentWindow.gotoGis = (form ) => {
          console.log(form);
          this.$emit( 'gotoGis', form )
        }

      },

      /**
       * 循环相应id重绘echarts
       */
      reDraw() {
        this.isEchartsData
          .filter(i => !i.hasDraw)
          .forEach(item => {
            this.reDrawEcharts(item.id, item.data)
            item.hasDraw = true
          })
      },

      /**
       * inputSearch 搜索
       */
       findInPage() {
        //判断搜索字符是否为空
        if (!this.inputSearch) {
          this.clearTokens()
          this.inputSearch = ''
          this.searchValue = ''
          this.$emit("allPageFn",'searchIndex', 0);
          this.$emit("allPageFn",'totalIndex', 0);
          return
        } else {
          //判断搜索条件是否已经改变
          if (this.inputSearch && this.inputSearch != this.searchValue) {
            this.searchValue = this.inputSearch
            this.clearTokens()
            let that = this
            this.getElementsToSearch().forEach(function(t) {
              window.findAndReplaceDOMText(t, {
                find: that.searchValue,
                wrap: 'mark',
                wrapClass: 'nw-token'
              })
            })
            this.setDataPositionAttribute()
            this.highlightCurrentToken()
          } else {
            this.searchValue = this.inputSearch
            this.highlightNext()
          }
        }
      },

      clearTokens() {
        const e = reportcontent.contentWindow.document.getElementsByClassName(
          'nw-token'
        )
        let t = []
        for (let n = 0; n < e.length; n++) t.push(e[n].parentNode)
        for (t = Array.from(new Set(t)); e.length; )
          e[0].replaceWith(...e[0].childNodes)
        t.forEach(function(e) {
          e.normalize()
        })
      },

      getElementsToSearch() {
        const e = []
        for (
          let t = 0;
          t < reportcontent.contentWindow.document.body.children.length;
          t++
        ) {
          let n = reportcontent.contentWindow.document.body.children[t]
          'style' !== n.tagName.toLowerCase() &&
            'script' !== n.tagName.toLowerCase() &&
            e.push(n)
        }
        return e
      },

      setDataPositionAttribute() {
        let e = 0,
          t = this.searchValue.length,
          n = t
        const i = reportcontent.contentWindow.document.getElementsByClassName(
          'nw-token'
        )
        ;[...i].forEach(
          function(i) {
            let o = i.innerText.length
            i.setAttribute(this.dataAttribute, e),
              o === t
                ? ((e += 1), (n = t))
                : ((n -= o), n < 1 && ((e += 1), (n = t)))
          }.bind(this)
        ),
          i || (e = 0),
          (this.totalIndex = e)

         this.$emit("allPageFn",'totalIndex', this.totalIndex);
      },

       highlightCurrentToken() {
        let e = reportcontent.contentWindow.document.getElementsByClassName(
            'nw-current-token'
          ),
          t = reportcontent.contentWindow.document.querySelectorAll(
            '.nw-token[' + this.dataAttribute + '="' + this.searchIndex + '"]'
          )
        e &&
          e.length &&
          ((e = [...e]),
          e.forEach(function(e) {
            e.classList.remove('nw-current-token')
          })),
          t &&
            t.length &&
            ((t = [...t]),
            t.forEach(function(e) {
              e.classList.add('nw-current-token')
            }))
          if(t){
             let textNode=t[0];
             while (textNode.className !='page-item'){
               textNode=textNode.parentNode
             }
             this.$emit("allPageFn",'inputPage',parseInt(textNode.id.split('page')[1])+1);
             t[0].scrollIntoView({
               behavior: 'smooth',
               block: 'start'})
          }
      },

      /**
       * 滚动监听
       */
      scrollListen() {
        if (!this.inputChange) {
          const pg=this.pageHeightA4 * this.scaleSize;
          const ctp = reportcontent.contentWindow.scrollY
          if (
            ctp > pg * this.inputPage ||
            ctp <= pg * (this.inputPage - 1)
          ) {
            let page = parseInt(ctp / pg) + 1
            if (page != this.inputPage) {
              console.log(page);
              this.$emit("allPageFn",'inputPage',page);
            }
          }
          if (this.lastInputPage != this.inputPage) {
            this.lastInputPage = this.inputPage
          }
          let that = this
          setTimeout(function() {
            that.nowAnchor(ctp)
          }, 100)
        }
      },

      /**
       * 再绘制一次echarts
       */
      reDrawEcharts(item, dataVal) {
        reportcontent.contentWindow.document.getElementById(item).innerHTML = ''
        reportcontent.contentWindow.document
          .getElementById(item)
          .removeAttribute('_echarts_instance_')
        this.homeEcharts = this.echarts.init(
          reportcontent.contentWindow.document.getElementById(item)
        )
        this.chartData = this.initChart(dataVal)
        this.homeEcharts.setOption(this.chartData, true)
      },

      /**
       * 获取被选中锚点
       */
      nowAnchor(offset_top) {
        const getTreeLists=this.getTreeList;
        const pageScroll = offset_top - this.pageHeightA4 * this.scaleSize * (this.inputPage - 1)
        if (getTreeLists.length > 0) {
          let selectIds = []
          selectIds=getTreeLists
            .filter(item => item.page == this.inputPage)
            .map(item => {
              return item.htmlId
            })
          let selectId = ''
          if (selectIds.length > 0) {
            for (var i = 0; i < selectIds.length; i++) {
              var classTop = reportcontent.contentWindow.document.getElementById(
                selectIds[i]
              ).offsetTop
              if (pageScroll + 10 >= classTop) {
                selectId = selectIds[i]
              }
            }
          } else {
            selectIds=getTreeLists
              .filter(item => item.page < this.inputPage)
              .map(item => {
                return item.htmlId
              })
            if (selectIds.length > 0) {
              selectId = selectIds[selectIds.length - 1]
            }
          }

          this.selectIndex = selectId
          this.$emit("allPageFn",'selectIndex',selectId);
        }
      },

      /**
       * 滚动定位
       */
      positioning(val) {
        if( reportcontent&&reportcontent.contentWindow.document.getElementById(val) ) {

          console.log(val);
          reportcontent.contentWindow.document.getElementById(val).scrollIntoView({
            block: 'start',
            behavior: 'auto',
            inline: 'center'
          }) //将元素滚动到浏览器窗口的可视区域
          setTimeout(() => {
            this.inputChange = false;

            this.showIframe = true;

            if(this.initOnce) {
              // 加载完成后提示父组件 initonce 为false

              this.$emit('closeInit');
            }

          }, 1000)
        }

      },

      /**
     * 获取报告页面 内容
     */
      getReport(reportId){
        if(!reportId)return false
        const that=this;
        this.api.getReportHtmlPages({reportId}).then(data => {
          this.$emit("allPageFn",'allPage',data.data.length);
          this.typographyPage(data.data)
          setTimeout(function() {
            if(that.inputSearch){
              that.findInPage()
            }
            if(that.initOnce || that.fixId === "1" ) {
              const a='page' + (that.inputPage-1);
              that.positioning(a);

            }else {
              that.positioning(that.fixId);
            }


          }, 100)
        })
      },

      /**
       * 排版报告页面
       */
      typographyPage(data){
          let echartValues = []
          let reportHtml =this.aHtml()
          data.forEach((item, pageIndex) => {
            reportHtml = reportHtml
              .concat('<div class="page-item" id="page' + pageIndex + '">')
              .concat(item.pageTop)
              .concat('<div class="w-content-wrap w-content page-box">')
              .concat(item.html)
              .concat('</div>')
              .concat(item.pageBottom)
              .concat('</div>')

            if (item.echartValue) {
              let echartValue = JSON.parse(item.echartValue)
              echartValue.forEach((items, index) => {
                echartValues.push({
                  id: items.id,
                  data: JSON.parse(items.data),
                  pageIndex: pageIndex,
                  hasDraw: false
                })
              })
            }
          })
          this.reportHtmls = reportHtml
          this.isEchartsData = echartValues
      },

      // 报告样式
      aHtml(){

        const body=`*{margin: 0;padding: 0;}body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB",SimSun,"Helvetica Neue",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";line-height:1.5;height:100%;margin:0;padding:0;background-color: #fff;transform-origin: 0 0;-ms-transform-origin: 0 0;-webkit-transform-origin: 0 0;-moz-transform-origin: 0 0;-o-transform-origin: 0 0; transform:scale(${this.scaleSize <= 1 ? 1.5 : this.scaleSize});}`
        const footer='.footer{background:#fff}'
        const pageItem=`.page-item{box-shadow: 0px 6px 13px 0px rgba(153, 153, 153, 0.19);border: 1px solid #ffffff;margin:10px auto;position:relative;box-sizing:border-box;background:#fff;width:793.7px;height:${this.pageHeightA4-10}px;}`
        const wordTitle1='.word-title-1{font-size:18px;font-weight:bold;text-align:center;color:rgb(0,0,0);letter-spacing:1px;word-spacing:1px;padding-bottom:10px;margin-top:0}'
        const wordTitle2='.word-title-2{font-size:16px;font-weight:bold;color:#333;letter-spacing:1px;text-align:left;word-spacing:1px;padding-bottom:10px;margin-top:0}'
        const wordTitle3='.word-title-3{font-size:14px;font-weight:bold;color:#333;letter-spacing:1px;text-align:left;word-spacing:1px;padding-bottom:10px;margin-top:0}'
        const wordTitle4='.word-title-4{font-size:12px;font-weight:bold;color:#333;letter-spacing:1px;text-align:left;word-spacing:1px;padding-bottom:10px;margin-top:0}'
        const wordText='.word-text{font-size:12px;overflow-wrap:break-word;letter-spacing:1px;text-align:left;color:#000;text-indent:2em;padding-bottom:20px;word-spacing:1px;margin-top:0}'
        const pageBox='.page-box{width:643.69px;height:956.3px;position:absolute;left:75px;top:75px;}'
        const wTable='.w-table{margin-bottom:10px;margin-top:0}'
        const catalogLine='.catalog-line{border-bottom:1px dashed;margin:0 5px;padding-left:0px;width:100%;z-index:0;height:12px;display:inline-block}'
        const catalogFirst='.catalog-first{padding-left:0px;font-size:12px;list-style:none;display:flex;width:100%;box-sizing:border-box}'
        const catalogSecond='.catalog-second{padding-left:20px;list-style:none;display:flex;font-size:12px;width:100%;box-sizing:border-box}'
        const catalogThird='.catalog-third{padding-left:40px;list-style:none;display:flex;font-size:12px;width:100%;box-sizing:border-box}'
        const catalogContent='.catalog-content{white-space:nowrap;text-indent:0}'
        const catalogPage='.catalog-page{position:absolute;right:0;z-index:1;text-indent:5px;background-color:#fff}'
        const fontBold='.font-bold{font-weight:bold}'
        const mBottom='.m-bottom{margin-bottom:10px}'
        const tableStyle='.el-table th,.el-table tr{color:#333;font-size:12px}.el-table th,.el-table thead.is-group th{color:#fff;background:#28487c;font-weight:400}.el-table th:last-child,.el-table tr td:last-child{border-right:none}.el-table td{font-size:12px}.el-table__header{width:100% !important}.el-table__body{width:100% !important}.el-table td,.el-table th.is-leaf,.el-table--border,.el-table--group{border-color:black}.el-table::before{background-color:#000!important}.el-table--group::after{background-color:#000!important}.el-table--border::after{background-color:#000!important}.el-table--border th{border-bottom:1px solid #000;border-right:1px solid #000}.f12{font-size:12px}.text_indent_2{text-indent:2em}.el-table td.is-center,.el-table th.is-center{text-align:center;padding:3px 0}.el-table--scrollable-x .el-table__body-wrapper{overflow-x:hidden}'
        const markT='mark.nw-token{background-color: #ff0;}mark.nw-token.nw-current-token{background-color: #38d878;}'
        // 报告页 可点击跳转的文字 样式
        const clickBlue = '.click-blue{ cursor:pointer; color: blue; }';

        return '<link rel="stylesheet" href="https://unpkg.zhimg.com/element-ui@2.14.0/lib/theme-chalk/index.css"/>' +
          '<style>' +body+footer+pageItem+wordTitle1+wordTitle2+wordTitle3+wordTitle4+wordText+pageBox+wTable+catalogLine+catalogFirst+catalogSecond+catalogThird+catalogContent+catalogPage+fontBold+mBottom+tableStyle+markT+clickBlue+
          ' </style>'
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>

